1498B - Box Fitting - CodeForces Solution


binary search bitmasks data structures greedy *1300

Please click on ads to support us..

Python Code:

t = int(input())

for _ in range(t):
  n, w = map(int,input().split())
  
  l_input = list(map(int,input().split()))
  l = sorted(l_input, reverse=True)
  
  d = {}
  for e in l:
    if e not in d:
      d[e] = 1
    else:
      d[e] += 1
  
  w_copy = w
  count = 0
  while n > 0:
    for e in d:
      while e <= w_copy and d[e] > 0:
        w_copy -= e
        d[e] -= 1
        n -= 1
    count += 1
    w_copy = w
  print(count)
    	 	 												 		 	  	

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define ll          long long
#define lli         long long int
#define vl          vector<ll>
#define vi          vector<int>
#define vs          vector<string>
#define pi          pair<int,int>
#define pl          pair<ll,ll>
#define all(a)      a.begin(),a.end()
#define mem(a,x)    memset(a,x,sizeof(a))
#define pb          push_back
#define mp          make_pair
#define F           first
#define S           second
#define f(a,b) for(int i=a;i<b;i++)
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
	int t;
	cin>>t;
	while(t--){
		int n,w;cin>>n>>w;
		multiset<int>nums;
		for(int i=0;i<n;i++){
			int x;cin>>x;
			nums.insert(x);
		}
		ll ans=1,sl=w;
		while (!nums.empty())
		{
			auto it=nums.upper_bound(sl);
			if(it!=nums.begin())
			{
				it--;
                int val = *it;
                sl -= val;
                nums.erase(it);
			}else{
				sl=w;
				ans++;
			}
		}
		cout<<ans<<endl;
		
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

101. Symmetric Tree
77. Combinations
46. Permutations
226. Invert Binary Tree
112. Path Sum
1556A - A Variety of Operations
136. Single Number
169. Majority Element
119. Pascal's Triangle II
409. Longest Palindrome
1574A - Regular Bracket Sequences
1574B - Combinatorics Homework
1567A - Domino Disaster
1593A - Elections
1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation
MAKEPAL Weird Palindrome Making
HILLSEQ Hill Sequence
MAXBRIDGE Maximise the bridges
WLDRPL Wildcard Replacement
1221. Split a String in Balanced Strings
1002. Find Common Characters
1602A - Two Subsequences
1555A - PizzaForces
1607B - Odd Grasshopper
1084A - The Fair Nut and Elevator
1440B - Sum of Medians
1032A - Kitchen Utensils
1501B - Napoleon Cake